package com.easy.back.utils.sendCode;


import cn.hutool.core.exceptions.UtilException;
import com.easy.back.pojo.EmailBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


/**
 * 发送邮件工具类
 *
 * @author RuoYu
 * @date 2022/11/18
 */
@Component
public class SendMailUtils {
    private static final Logger logger = LoggerFactory.getLogger(SendMailUtils.class);

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;//发送人

    //    private String to = "983985701@qq.com";//接收人

    //邮件主题
    @Value("${mail.subject}")
    private String subject;

    //邮件内容
    @Value("${mail.prefixTest}")
    private String prefixTest = "";

    @Value("${mail.suffixTest}")
    private String suffixTest = "";


    /**
     * 发送邮件
     *
     * @param to   来源
     * @param code 验证码
     *///    @Async
    public void sendMail(String to, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from + "(随易租)");
            message.setTo(to);
            message.setSubject(subject);
            message.setText(prefixTest + code + suffixTest);
            javaMailSender.send(message);
        } catch (UtilException e) {
            logger.error("邮箱工具类异常信息为:{}", e.getMessage());
        }
    }

    //邮件主题
    @Value("${riskWaring.waringSubject}")
    private String waringSubject;

    //邮件内容
    @Value("${riskWaring.waring1}")
    private String waring1;

    @Value("${riskWaring.waring2}")
    private String waring2;

    @Value("${riskWaring.waring3}")
    private String waring3;

    @Value("${riskWaring.waring4}")
    private String waring4;


    /**
     * 发送错误邮件
     * 发送 登录异常 邮件
     *
     * @param emailBody 邮件正文
     */
    public void sendErrorMail(EmailBody emailBody) {

        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from + "(随易租)");
            helper.setTo(emailBody.getSource());
            helper.setSubject(waringSubject);
            helper.setText(waring1 + emailBody.getUserName() + waring2 + emailBody.getTime() + waring3 + emailBody.getIp() + "(" + emailBody.getIpAddress() + ")" + waring4, true);

        } catch (MessagingException e) {
            logger.error("邮箱工具类异常信息为:{}", e.getMessage());
        }
        javaMailSender.send(message);
    }

}

